package com.nil.codegen.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import com.nil.codegen.config.AppContext;

import java.time.LocalDateTime;
import java.util.Date;

@Component
public class MpMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // createTime 这个字段与pojo类中字段对应
        if (metaObject.hasGetter("createTime") && metaObject.getValue("createTime") == null) {
            this.setFieldValByName("createTime", new Date(), metaObject);
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (AppContext.getCurrentUser() != null) {
            this.setFieldValByName("createUser", AppContext.getCurrentUser().getId(), metaObject);
            this.setFieldValByName("updateUser", AppContext.getCurrentUser().getId(), metaObject);
            this.setFieldValByName("deleteFlag", "0", metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (AppContext.getCurrentUser() != null) {
            this.setFieldValByName("updateUser", AppContext.getCurrentUser().getId(), metaObject);
        }


    }
}
